package logic

import (
	"context"
	"jd-mall/jd_srv/jdsrvclient"
	"jd-mall/pkg"
	"net/http"
	"path/filepath"

	"jd-mall/api/internal/svc"
	"jd-mall/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UploadLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUploadLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UploadLogic {
	return &UploadLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UploadLogic) Upload(req *http.Request, t *types.UploadRequest) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line
	file, m, err := req.FormFile("image")
	if err != nil {
		return &types.Response{
			Code: -1,
			Msg:  "图片获取失败",
			Data: nil,
		}, nil
	}
	if filepath.Ext(m.Filename) != ".png" {
		return &types.Response{
			Code: -1,
			Msg:  "仅允许上传png格式图片",
			Data: nil,
		}, nil
	}
	if m.Size > (1024 * 10) {
		return &types.Response{
			Code: -1,
			Msg:  "仅允许上传10KB以内大小的图片",
			Data: nil,
		}, nil
	}

	upload, err := pkg.Upload(file, m)
	if err != nil {
		return &types.Response{
			Code: -1,
			Msg:  "图片上传失败",
			Data: err.Error(),
		}, nil
	}

	response, _ := l.svcCtx.JdSrv.Upload(l.ctx, &jdsrvclient.UploadRequest{
		ShopId:   int64(t.ShopId),
		ImageUrl: upload,
	})

	res := map[string]interface{}{
		"ImageUrl":    upload,
		"ShopImageId": response,
	}

	return &types.Response{
		Code: 200,
		Msg:  "图片上传成功",
		Data: res,
	}, nil
}
